package com.wochao.common.utils;

import com.wochao.common.exception.ReturnToFrontException;
import com.wochao.common.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * 自定义JWT配置
 */
public class JwtUtil {

    private static long tokenExpiration = 3600000 * 24 * 365;
    private static SecretKey tokenSignKey = Keys.hmacShaKeyFor("2lshTYZB2Zc6LkiRmkWrcIiSDZHQ1fgU".getBytes());

    /**
     * 创建JWT工具类
     *
     * @param userId
     * @param username
     * @return
     */
    public static String createToken(long userId, String username) {
        String token = Jwts.builder()
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .setSubject("LOGIN_USER")
                .claim("userId", userId)
                .claim("username", username)
                .signWith(tokenSignKey)
                .compact();

        return token;
    }

    /**
     * 校验JWT合法性
     *
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        if (token == null) {
            throw new ReturnToFrontException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(tokenSignKey).build();
            return jwtParser.parseClaimsJws(token).getBody();
        } catch (ExpiredJwtException e) {
            throw new ReturnToFrontException(ResultCodeEnum.TOKEN_EXPIRED);
        } catch (JwtException e) {
            throw new ReturnToFrontException(ResultCodeEnum.TOKEN_INVALID);
        }
    }
}
